<template>
  <el-form
    ref="formRef"
    :model="form"
    label-width="120px"
    :rules="rules">
    <el-form-item label="所属应用">
      <el-tag
        v-if="form.app && form.app.group_id"
        size="large"
        style="margin-right: 10px;">
        {{ form.app.group_name }}
      </el-tag>
      <el-button type="primary" @click="handleShowAppSelectWin">选择应用</el-button>
    </el-form-item>
    <el-form-item label="切面位置" prop="type">
      <div style="margin-bottom: 5px;display: block;">
        <el-radio-group v-model="form.type" class="radio-avg-width">
          <el-radio-button :label="1">微接口（API）</el-radio-button>
          <el-radio-button :label="2">微函数（Func）</el-radio-button>
          <el-radio-button :label="3">表单接口（Form）</el-radio-button>
        </el-radio-group>
      </div>
      <el-radio-group v-model="form.action_type" v-if="form.type !== 2" class="radio-avg-width" style="width:400px;">
        <el-radio-button :label="1">替换</el-radio-button>
        <el-radio-button :label="2">前置 AOP</el-radio-button>
        <el-radio-button :label="3">后置 AOP</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="表单" v-if="form.type === 3">
        <el-tag v-if="form.form && form.form.form_id" size="medium" style="margin-right: 10px;">
          {{ form.form.form_name }}
        </el-tag>
        <el-button type="primary" @click="handleShowFormSelectWin">选择表单</el-button>
    </el-form-item>
    <el-form-item label="钩子目标" prop="hook">
      <el-select v-if="form.type === 2" v-model="form.hook" clearable allow-create filterable default-first-option
                 popper-class="select-vt" style="width: 300px;">
        <el-option value="geneLoginname" label="geneLoginname">
          <span class="sop-label">geneLoginname</span>
          <span class="sop-tip">生成登录名</span>
        </el-option>
        <el-option value="geneInitPassword" label="geneInitPassword">
          <span class="sop-label">geneInitPassword</span>
          <span class="sop-tip">生成初始化密码</span>
        </el-option>
        <el-option value="getDownloadExcelData" label="getDownloadExcelData">
          <span class="sop-label">getDownloadExcelData</span>
          <span class="sop-tip">Excel下载数据</span>
        </el-option>
        <el-option value="sendSms" label="sendSms">
          <span class="sop-label">sendSms</span>
          <span class="sop-tip">发送短信消息</span>
        </el-option>
        <el-option value="sendEmail" label="sendEmail">
          <span class="sop-label">sendEmail</span>
          <span class="sop-tip">发送邮件消息</span>
        </el-option>
        <el-option value="getCasLoginAccount" label="getCasLoginAccount">
          <span class="sop-label">getCasLoginAccount</span>
          <span class="sop-tip">通过CAS方式登录查询用户</span>
        </el-option>
      </el-select>
      <el-input v-else v-model="form.hook" placeholder="hook，如：/register/submit、sendSms 等"></el-input>
    </el-form-item>
    <el-form-item label="钩子微接口" v-if="form.type !== 2">
      <el-tag v-if="form.api && form.api.api_id" size="medium" style="margin-right: 10px;">
        {{ form.api.api_name }}
      </el-tag>
      <el-button type="primary" @click="handleShowApiWin" size="mini">选择微接口</el-button>
    </el-form-item>
    <el-form-item label="钩子微函数" v-if="form.type === 2">
      <el-tag v-if="form.func && form.func.func_id" size="medium" style="margin-right: 10px;">
        {{ form.func.func_name }}
      </el-tag>
      <el-button type="primary" @click="handleShowFuncWin" size="mini">选择微函数</el-button>
    </el-form-item>

    <el-form-item
      class="form-item-center"
      label=""
      label-width="0px"
      style="text-align: center;margin-top: 30px;">
      <el-button
        size="large"
        type="primary"
        @click="handleSubmitCreateApi"> 提交 </el-button>
      <el-button
        size="large"
        @click="handleCancel"> 取消 </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import _ from 'lodash';
import { ElMessage } from 'element-plus';
import {$WinApps, $WinForms} from '@jzl/comps'
import {$WinFuncs, $WinMicrosvc} from "@jzl/comps-mg";

const props = defineProps({
  actionType: String,
  currentData: Object,
  module: Object
});

const emit = defineEmits(['close']);

const DEFAULT_FORM = {
  app_id: null,
  scope_type: 3,
  type: 1,
  action_type: 1,
  form_id: null,
  hook: '',
  api_id: null,
  func_id: null,

  app: {},
  form: {},
  func: {},
  api: {}
};

const form = ref(_.cloneDeep(DEFAULT_FORM));
const rules = {
  hook: [
    { required: true, message: '请输入钩子目标', trigger: 'blur' }
  ]
};

const init = () => {
  let formValue = null;
  let data = _.cloneDeep(props.currentData);

  if (data && data.id) {
    formValue = data;
  } else {
    formValue = _.defaults(data || {}, DEFAULT_FORM);
  }

  form.value = formValue || {};
};

const handleSubmitCreateApi = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'id');
  let ret = null;

  if (data.type === 2) {
    data.action_type = 1;
  }

  if (id) {
    ret = await props.$japi.hook.update(data);
  } else {
    ret = await props.$japi.hook.create(data);
  }

  if (ret) {
    ElMessage.success('操作成功！');
    handleCancel();
  }
};

const handleCancel = (flag) => {
  emit('close', flag);
};

const handleShowAppSelectWin = () => {
  $WinApps({
    onConfirm: async (app) => {
      if (!app || !app.group_id) {
        return;
      }
      form.value.app = app;
      form.value.app_id = app.group_id;
    },
    onCancel: () => {}
  });
};

const handleShowFormSelectWin = () => {
  $WinForms({
    type: 'form',
    onSelect: (info) => {
      let formInfo = _.get(info, 'form');
      if (!formInfo || !formInfo.form_id) return;

      form.value.form_id = formInfo.form_id;
      form.value.form = formInfo;
    }
  });
};

const handleShowApiWin = () => {
  $WinMicrosvc({
    onSelect: async (apiInfo) => {
      let apiId = _.get(apiInfo, "api_id");
      if (!apiInfo) return;

      form.value.api = apiInfo;
      form.value.api_id = apiId;
    }
  });
};

const handleShowFuncWin = () => {
  $WinFuncs({
    onSelect: (func) => {
      if (!func || !func.func_id) return;

      form.value.func = func;
      form.value.func_id = _.get(func, "func_id");
    }
  });
};

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, { deep: true });
</script>
